<?php

namespace lc\activity\model;

use lc\cache\redis\Redis;
use think\facade\Db;
use think\Model;

class LotteryConfig extends Model
{
	protected $table = 'lottery_configs';
    protected $pk    = 'l_id';
    protected $autoWriteTimestamp = false;

    /**
     * @var 抽奖类型奖池随机
     */
    const LOTTERY_TYPE_RANDOM = 1;

    /**
     * @var 抽奖类型列表随机
     */
    const LOTTERY_TYPE_LIST = 2;

	/**
	 * @var Redis 抽奖
	 */
	const LOTTERY_REDIS_YES = 1;

	/**
	 * @var 非 Redis 抽奖
	 */
	const LOTTERY_REDIS_NO  = 0;

	/**
	 * @var 无抽奖次数
	 */
	const USER_NO_COUNT = 301;

	/**
	 * @var 当前时间不允许中奖
	 */
    const TIME_LIMIT = 302;

	/**
	 * @var IP当日中奖次数上限
	 */
    const IP_TODAY_WIN_LIMIT = 303;

	/**
	 * @var IP最大中奖次数上限
	 */
    const IP_MAX_WIN_LIMIT = 304;

	/**
	 * @var 奖池暂无奖品
	 */
    const NO_AWARD = 305;

	/**
	 * @var 发奖失败（虚拟奖）
	 */
    const AWARD_SEND_FAIL = 306;

	/**
	 * @var 用户当日参与次数上限
	 */
    const USER_TODAY_JOIN_LIMIT = 307;

	/**
	 * @var 用户最大参与次数上限
	 */
    const USER_MAX_JOIN_LIMIT = 308;

	/**
	 * @var 接口请求频繁
	 */
    const REQUEST_FREQUENT = 309;

	/**
	 * @var 用户当日中奖次数上限
	 */
    const USER_TODAY_WIN_LIMIT = 310;

	/**
	 * @var 用户最大中奖次数上限
	 */
    const USER_MAX_WIN_LIMIT = 311;

	/**
	 * @var 随机未中奖
	 */
    const RANDOM_NOT_WIN = 312;

	/**
	 * @var 扣除抽奖次数失败
	 */
    const REDUCE_USER_COUNT_FAIL = 313;

	/**
	 * @var 更新奖池（库存）失败
	 */
    const UPDATE_STOCK_FAIL = 314;

	/**
	 * @var 默认中奖
	 */
    const WIN_DEFAULT = 315;

	/**
	 * @var 最大参与用户数上限
	 */
	const MAX_JOIN_USER_LIMIT = 316;

	/**
	 * @var 最大参与次数上限
	 */
	const MAX_JOIN_COUNT_LIMIT = 317;

    /**
     * @var 活动状态异常
     */
    const STATUS_EXCEPTION = 1000;

    public static $awardType = [
        0 => '叠加，发放所有当前时间奖池，条件为：a_start <= time()',
        1 => '不叠加，仅发放当前时段奖池，条件为：a_start = strtotime(date(\'Y-m-d H:00:00\'))',
        2 => '不叠加，仅发放当天时段奖池，条件为：a_start = strtotime(\'today\')'
    ];

    public static $awardSendType = [
        1 => '普通奖品',
        2 => '微信现金红包',
        3 => '企业支付零钱红包'
    ];

	/**
	 * @desc 	保存或更新 Redis 抽奖配置信息
	 * @param 	Redis 			$redis
	 * @param 	string 			$lotKey		hash key
	 * @param 	LotteryConfig 	$dbConfig	数据库配置
	 */
	public static function setRedisLotteryConfig(Redis $redis, string $lotKey, LotteryConfig $dbConfig)
	{
		$fields = [
			'l_name', 'l_pid', 'l_lottery_type', 'l_start_time', 'l_end_time', 'l_win_start', 'l_win_end', 'l_rand', 'l_daily_count',
			'l_max_count', 'l_day_win_count', 'l_max_win_count', 'l_daily_ip_limit', 'l_max_ip_limit', 'l_curr_join_user',
			'l_max_join_user', 'l_curr_join_count', 'l_max_join_count', 'l_type', 'l_field', 'l_field_val', 'l_default_award'
		];
		foreach ($fields as $key) {
			$redis->hSet($lotKey, $key, $dbConfig->$key);
		}
	}

    public static function createTableUser($id)
    {
        Db::execute("DROP TABLE IF EXISTS `g_{$id}_user`;");
        $sql = "
            CREATE TABLE `g_{$id}_user` (
              `u_id` bigint(13) unsigned NOT NULL AUTO_INCREMENT,
              `u_uid` int(10) unsigned DEFAULT NULL COMMENT '用户ID',
              `u_openid` varchar(50) DEFAULT NULL,
              `u_nick` varchar(100) DEFAULT NULL COMMENT '昵称',
              `u_headimg` varchar(200) DEFAULT NULL COMMENT '头像',
              `u_name` varchar(20) DEFAULT NULL COMMENT '姓名，抽奖器发红包验证身份时，需要该参数',
              `u_count` int(10) unsigned DEFAULT '0' COMMENT '抽奖次数',
              `u_black` tinyint(1) unsigned DEFAULT '0' COMMENT '是否为黑名单用户',
              `u_created` datetime DEFAULT NULL COMMENT '第一次进入时间戳',
              `u_updated` datetime DEFAULT NULL COMMENT '重置游戏次数时间戳',
              PRIMARY KEY (`u_id`),
              UNIQUE KEY `u_openid` (`u_openid`),
              UNIQUE KEY `u_uid` (`u_uid`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
        ";
        Db::execute($sql);
    }

    public static function createTableUserExtra($id)
    {
        Db::execute("DROP TABLE IF EXISTS `g_{$id}_user_extra`;");
        $sql = "
            CREATE TABLE `g_{$id}_user_extra` (
              `ue_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `ue_uid` int(10) unsigned DEFAULT NULL COMMENT '用户ID',
              `ue_last_day` int(10) unsigned DEFAULT '0' COMMENT '最后参与时间',
              `ue_day_join_count` int(10) unsigned DEFAULT '0' COMMENT '最后参与日参与次数',
              `ue_max_join_count` int(10) unsigned DEFAULT '0' COMMENT '活动期间参与次数',
              `ue_day_win_count` int(10) unsigned DEFAULT '0' COMMENT '最后参与日中奖次数',
              `ue_max_win_count` int(10) unsigned DEFAULT '0' COMMENT '活动期间中奖次数',
              PRIMARY KEY (`ue_id`),
              KEY `ue_uid` (`ue_uid`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        ";
        Db::execute($sql);
    }

    public static function createTableLotteryLogs($id)
    {
        Db::execute("DROP TABLE IF EXISTS `g_{$id}_lottery_logs`;");
        $sql = "
            CREATE TABLE `g_{$id}_lottery_logs` (
              `ll_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
              `ll_uid` bigint(13) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
              `ll_phone` varchar(20) DEFAULT NULL COMMENT '抽奖时所⽤电话号码',
              `ll_key` varchar(40) DEFAULT NULL,
              `ll_status` varchar(100) DEFAULT NULL COMMENT '中奖描述',
              `ll_ip` varchar(20) DEFAULT NULL,
              `ll_day` int(10) unsigned NOT NULL COMMENT '抽奖当天时间戳',
              `ll_create` datetime DEFAULT NULL COMMENT '抽奖⽇期',
              `ll_marks` varchar(100) DEFAULT NULL,
              PRIMARY KEY (`ll_id`),
              UNIQUE KEY `ll_key` (`ll_key`),
              KEY `ll_uid` (`ll_uid`),
              KEY `ll_day` (`ll_day`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='用户抽奖记录表';
        ";
        Db::execute($sql);
    }

    public static function createTableIps($id)
    {
        Db::execute("DROP TABLE IF EXISTS `g_{$id}_ips`;");
        $sql = "
            CREATE TABLE `g_{$id}_ips` (
              `i_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `i_ip` varchar(20) DEFAULT NULL,
              `i_day_req_count` int(10) unsigned DEFAULT '1' COMMENT '单日请求次数',
              `i_max_req_count` int(10) unsigned DEFAULT '0' COMMENT '最大请求',
              `i_day_join_count` int(10) unsigned DEFAULT '0' COMMENT '单日参与',
              `i_max_join_count` int(10) unsigned DEFAULT '0' COMMENT '最大参与',
              `i_day_win_count` int(10) unsigned DEFAULT '0' COMMENT '当日中奖',
              `i_max_win_count` int(10) unsigned DEFAULT '0' COMMENT '最大中奖',
              `i_last_day` int(10) unsigned DEFAULT NULL COMMENT '日期',
              PRIMARY KEY (`i_id`),
              UNIQUE KEY `i_ip` (`i_ip`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
        ";
        Db::execute($sql);
    }

    public static function createTableAwardList($id)
    {
        Db::execute("DROP TABLE IF EXISTS `g_{$id}_award_list`;");
        $sql = "
            CREATE TABLE `g_{$id}_award_list` (
              `a_id` int(10) NOT NULL AUTO_INCREMENT,
              `a_awardid` tinyint(2) unsigned DEFAULT NULL,
              `a_award_type` tinyint(4) unsigned DEFAULT '1' COMMENT '奖品类型',
              `a_awardname` varchar(100) DEFAULT NULL,
              `a_number` int(10) unsigned NOT NULL COMMENT '奖品数量',
              `a_price` int(4) unsigned DEFAULT NULL COMMENT '奖品价值，用于红包',
              `a_received` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '已领取数量',
              `a_rate` int(10) unsigned DEFAULT '0' COMMENT '中奖几率',
              `a_state` tinyint(1) unsigned DEFAULT '1' COMMENT '奖品状态，默认1，上架中，0下架',
              PRIMARY KEY (`a_id`),
              KEY `a_award` (`a_awardid`) USING BTREE
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
        ";
        Db::execute($sql);
    }

    public static function createTableAward($id)
    {
        Db::execute("DROP TABLE IF EXISTS `g_{$id}_award`;");
        $sql = "
            CREATE TABLE `g_{$id}_award` (
              `a_id` int(10) NOT NULL AUTO_INCREMENT,
              `a_awardid` tinyint(2) DEFAULT NULL,
              `a_award_type` tinyint(2) DEFAULT '1' COMMENT '奖品类型',
              `a_awardname` varchar(64) DEFAULT NULL,
              `a_price` int(10) unsigned DEFAULT '0' COMMENT '物品价值，一般用于红包奖品，单位分',
              `a_code` varchar(32) DEFAULT NULL,
              `a_start` int(10) DEFAULT NULL,
              `a_state` tinyint(1) unsigned DEFAULT '1' COMMENT '奖品状态，默认1，上架中，0下架',
              `a_uid` int(10) DEFAULT '0',
              `a_sendtime` int(10) DEFAULT '0',
              `a_ip` varchar(20) DEFAULT NULL,
              `a_exchange` tinyint(1) DEFAULT '0' COMMENT '是否核销',
              PRIMARY KEY (`a_id`),
              KEY `a_award` (`a_awardid`) USING BTREE
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
        ";
        Db::execute($sql);
    }

	public static function createWinnerTable($id)
	{
		Db::execute("DROP TABLE IF EXISTS `g_{$id}_winner`;");
		$sql = "
			CREATE TABLE `g_{$id}_winner` (
			  `w_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
			  `w_uid` int(10) unsigned DEFAULT NULL COMMENT '中奖用户ID',
			  `w_aid` int(10) unsigned DEFAULT NULL COMMENT 'award表或award_id表ID',
			  `w_award_id` int(10) unsigned DEFAULT NULL COMMENT '奖品ID',
			  `w_award_code` VARCHAR(32) DEFAULT NULL COMMENT '奖品码',
			  `w_award_name` varchar(64) DEFAULT NULL COMMENT '奖品名称',
			  `w_award_price` int(10) DEFAULT '0' COMMENT '奖品价值',
			  `w_win_time` datetime DEFAULT NULL COMMENT '中奖时间',
			  `w_ip` varchar(20) DEFAULT NULL COMMENT '中奖IP',
			  `w_is_recv` tinyint(1) unsigned DEFAULT '0' COMMENT '是否已领取',
			  PRIMARY KEY (`w_id`),
			  KEY `w_uid` (`w_uid`),
			  KEY `w_aid` (`w_aid`),
			  KEY `w_award_id` (`w_award_id`)
			) ENGINE=InnoDB DEFAULT CHARSET=utf8;
		";
		Db::execute($sql);
    }
}